package com.xxx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xxx.mapper.ClassInfoMapper;
import com.xxx.pojo.ClassInfo;
import com.xxx.service.ClassInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ClassInfoServiceImpl implements ClassInfoService {

    @Autowired
    private ClassInfoMapper mapper;

    @Override
    public IPage getByPage(IPage iPage,String name) {

        LambdaQueryWrapper<ClassInfo> lqw = new LambdaQueryWrapper<>();
        lqw.like(null != name && !"".equals(name.trim()),ClassInfo::getTypesName,name).orderByAsc(ClassInfo::getOrder);

        IPage page = mapper.selectPage(iPage, lqw);

        return page;
    }

    @Override
    public int deleteById(Long id) {

        int i = mapper.deleteById(id);

        return i;
    }

    @Override
    public int save(ClassInfo classInfo) {

        Long count = mapper.selectCount(new LambdaQueryWrapper<ClassInfo>()
                .eq(ClassInfo::getTypesName, classInfo.getTypesName()));

        return count == 0L? mapper.insert(classInfo) : -1;
    }

    @Override
    public int update(ClassInfo classInfo) {
        ClassInfo one = mapper.selectOne(new LambdaQueryWrapper<ClassInfo>()
                .eq(ClassInfo::getTypesName, classInfo.getTypesName()));

        int i =0;
        if (one == null){
            return mapper.updateById(classInfo);
        }
        if (one.getOrder() == classInfo.getOrder()){
            if (!one.getTypes().equals(classInfo.getTypes()) || !one.getTypesName().equals(classInfo.getTypesName())){
                i = mapper.updateById(classInfo);
            }
        }else {
            return one.getTypesName().equals(classInfo.getTypesName()) ? i : mapper.updateById(classInfo);
        }
        return i;
    }

    @Override
    public List<ClassInfo> getTypesName(String types) {

        LambdaQueryWrapper<ClassInfo> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ClassInfo::getTypes,types);
        List<ClassInfo> list = mapper.selectList(lqw);

        return list;
    }

    @Override
    public ClassInfo getTypesNameById(Long id) {

        LambdaQueryWrapper<ClassInfo> lqw = new LambdaQueryWrapper<>();
        lqw.select(ClassInfo::getTypesName).eq(ClassInfo::getOrder,id);

        ClassInfo classInfo = mapper.selectOne(lqw);
        return classInfo;
    }


}
